package cn.com.lyb.flink.split;

import cn.com.lyb.flink.bean.WaterSensor;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class SideOutputDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> map = env.socketTextStream("172.32.1.6", 1234).
                map(new WaterSensorMapFunction());
        // 使用测输出流 实现分流


        // s1 放入的测流
        // 创建OutputTag对象
        // 第一个参数  标签名 第二个参数 放入输出流的 数据的 类型  Typeinformation
        OutputTag<WaterSensor> s1 = new OutputTag<WaterSensor>("s1", Types.POJO(WaterSensor.class)){};
        OutputTag<WaterSensor> s2 = new OutputTag<WaterSensor>("s2", Types.POJO(WaterSensor.class)){};

        // 定义主流测输出类型
        SingleOutputStreamOperator<WaterSensor> process = map.process(new ProcessFunction<WaterSensor, WaterSensor>() {
            @Override
            public void processElement(WaterSensor value, Context cxt, Collector<WaterSensor> out) throws Exception {
                String id = value.getId();
                if ("s1".equals(id)) {

                    cxt.output(s1, value);
                } else if ("s2".equals(id)) {
                    // s2 放入的测流
                    cxt.output(s2, value);
                } else {
                    // 其他非s1, s2 的数据放入到主流中
                    out.collect(value);
                }
            }
        });
        // 打印主流数据
        process.print("主流数据");

        // 打印测流 s1
        process.getSideOutput(s1).print("s1 测流数据");
        // 打印测流 s2
        process.getSideOutput(s2).print("s2 测流数据");

        env.execute();
    }
}
